<template>
  <el-progress class="top-progress" :percentage="percentage" :stroke-width="4" />
</template>

<script setup lang="ts">
import { useSysStore } from "@/store";
import { ref, watch, onMounted, onUnmounted } from "vue";

const sysStore = useSysStore();
const percentage = ref(0);
let animationFrameId: number | null = null;

// 正常速度的动画（0 → 40%，缓慢填充）
const startSlowAnimation = () => {
  const duration = 2000; // 慢速动画总时长（ms）
  const startTime = Date.now();

  const update = () => {
    const elapsed = Date.now() - startTime;
    const progress = Math.min(elapsed / duration, 1);
    percentage.value = progress * 40;

    if (progress < 1 && !sysStore.processFinish) {
      animationFrameId = requestAnimationFrame(update);
    } else if (sysStore.processFinish) {
      // 如果 processFinish 为 true，直接跳到 100%
      percentage.value = 100;
      sysStore.setProcessFinish(false);
    }
  };

  animationFrameId = requestAnimationFrame(update);
};

// 监听 sysStore.processFinish，如果为 true 则瞬间完成
watch(
  () => sysStore.processFinish,
  (newVal) => {
    if (newVal) {
      // 取消当前) {
      // 取消当前动画
      if (animationFrameId) {
        cancelAnimationFrame(animationFrameId);
      }
      // 直接跳到 100%
      percentage.value = 100;
    }
  }
);

watch(
  () => percentage.value,
  (newVal) => {
    if (newVal >= 100) {
      // 执行你的逻辑，例如：
      // 隐藏进度条
      setTimeout(() => {
        sysStore.setIsProcess(false);
      }, 500);
    }
  }
);

onMounted(() => {
  startSlowAnimation();
});

// 组件卸载时清理动画
onUnmounted(() => {
  if (animationFrameId) {
    cancelAnimationFrame(animationFrameId);
  }
});
</script>

<style lang="scss" scoped>
.top-progress {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  z-index: 9999;
  transition: all 0.1s linear;

  /* 微调动画平滑度 */
  :deep(.el-progress-bar__inner) {
    background-color: var(--el-color-primary-light-3);
  }
}
</style>
